package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.entity.BackResponseEntity;
import com.example.demo.entity.BookFavorites;
import com.example.demo.entity.BooksInformation;
import com.example.demo.entity.Login;
import com.example.demo.entity.requestJson.DeleteReq;
import com.example.demo.entity.requestJson.FavoriteBookReq;
import com.example.demo.entity.requestJson.QueryFavBookReq;
import com.example.demo.entity.responseJson.BookshelfBInformationRes;
import com.example.demo.entity.responseJson.ListResult;
import com.example.demo.enums.ErrCodeEnum;
import com.example.demo.mapper.*;
import com.example.demo.service.ABookFavoritesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author : 洪俊新
 * @date : 2021/3/10 11:43
 * @description:
 */
@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class ABookFavoritesServiceImpl implements ABookFavoritesService {
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private BookshelefMapper bookshelefMapper;
    @Autowired
    private BooksInformationMapper booksInformationMapper;
    @Autowired
    private BookFavoritesMapper bookFavoritesMapper;
    @Autowired
    private ABookfavoriteBookMapper aBookfavoriteBookMapper;
    @Autowired
    private LoginMapper loginMapper;

    /**
     * 收藏书本
     * 1.调用接口查看是否收藏
     * 2.点击收藏
     * 3.图标变成已收藏，书本放入书架，展示在个人中心的收藏作品中
     * */
    @Override
    public BackResponseEntity<Object> insertFavoriteBook(FavoriteBookReq favoriteBookReq){
        String bookId = null;
        String userId = null;

        if(!ObjectUtils.isEmpty(favoriteBookReq.getBookId())){
            bookId = favoriteBookReq.getBookId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(favoriteBookReq.getUserId())){
            userId = favoriteBookReq.getUserId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(bookId) || ObjectUtils.isEmpty(userId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        LambdaQueryWrapper<Login> queryWrapper = new QueryWrapper<Login>().lambda();
        queryWrapper.select(Login::getBookshelfId)
                .eq(Login::getLoginId,userId);
        Login login = loginMapper.selectOne(queryWrapper);

        LambdaQueryWrapper<BooksInformation> wrapper = new QueryWrapper<BooksInformation>().lambda();
        wrapper.select(BooksInformation::getBookName)
                .eq(BooksInformation::getBooksId,bookId);
        BooksInformation booksInformation1 = booksInformationMapper.selectOne(wrapper);

        BookFavorites bookFavorites = new BookFavorites();
        bookFavorites.setBookId(bookId);
        bookFavorites.setBookname(booksInformation1.getBookName());
        bookFavorites.setUserId(userId);
        bookFavorites.setUserName(login.getLoginNickname());
        bookFavorites.setUserImg(login.getLoginPic());
        bookFavorites.setFavoritesTime(LocalDateTime.now());

        int i = bookFavoritesMapper.insert(bookFavorites);

        if(i > 0){

            BooksInformation booksInformation = new BooksInformation();
            int count = aBookfavoriteBookMapper.queryFavoriteCount(Wrappers.<BookFavorites>query().eq("books_id", bookId)) +1;
            booksInformation.setBooksId(bookId);
            booksInformation.setFavoritesCount(count);

            int m = booksInformationMapper.updateBooksInformation(booksInformation);

            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "收藏成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1013, "收藏失败");
        }
    }

    /**
     * 查询书架所有书籍,也用于查看个人主页收藏作品
     * 传入userid
     * */
    @Override
    public BackResponseEntity<ListResult<List<BookshelfBInformationRes>>> querybookshelefBook(DeleteReq deleteReq){
        String id = null;

        if(!ObjectUtils.isEmpty(deleteReq.getId())){
            id = deleteReq.getId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(id)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }

        List<BookshelfBInformationRes> list = aBookfavoriteBookMapper.querybookshelefBook(Wrappers.<BookFavorites>query().eq("user_id", id));

        int count = aBookfavoriteBookMapper.countbookshelefBook(Wrappers.<BookFavorites>query().eq("user_id", id));
        ListResult<List<BookshelfBInformationRes>> listResult = new ListResult((int)count, list);

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, listResult, "");

    }

    /**
     * 是否收藏该书
     * */
    @Override
    public BackResponseEntity<Object> isfavoriteBook(FavoriteBookReq favoriteBookReq){

        if(ObjectUtils.isEmpty(favoriteBookReq.getUserId()) || ObjectUtils.isEmpty(favoriteBookReq.getBookId())){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        if(aBookfavoriteBookMapper.isFavoriteBook(Wrappers.<BookFavorites>query().eq("user_id", favoriteBookReq.getUserId())
                                                                                    .eq("book_id", favoriteBookReq.getBookId())) == 0){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1021, "未收藏书籍");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1020, "已收藏该书籍");
        }
    }

    /**
     * 取消收藏
     * 1.进行取消操作
     * 2.相应的收藏数减少
     * 3.删除关注表中的记录
     * */
    @Override
    public BackResponseEntity<Object> unSubscribeBook(FavoriteBookReq favoriteBookReq){
        String userId = null;
        String bookId = null;

        if(!ObjectUtils.isEmpty(favoriteBookReq.getBookId())){
            bookId = favoriteBookReq.getBookId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(favoriteBookReq.getUserId())){
            userId = favoriteBookReq.getUserId()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(bookId)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "参数缺失");
        }
        BookFavorites bookFavorites = new BookFavorites();
        bookFavorites.setUserId(userId);
        bookFavorites.setBookId(bookId);
        int i = bookFavoritesMapper.deleteBookFavoritesByEntity(bookFavorites);

        if( i > 0 ){
            BooksInformation booksInformation = new BooksInformation();
            int count = aBookfavoriteBookMapper.queryFavoriteCount(Wrappers.<BookFavorites>query().eq("books_id", favoriteBookReq.getBookId()))-1;

            booksInformation.setBooksId(bookId);
            booksInformation.setFavoritesCount(count);
            int m = booksInformationMapper.updateBooksInformation(booksInformation);

            return BackResponseEntity.success(ErrCodeEnum.unknown_0, "取消收藏注成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1017, "取消收藏失败");
        }

    }


    /**
     * 模糊查询收藏书籍（用户书架搜索）
     * */
    @Override
    public BackResponseEntity<List<BookshelfBInformationRes>> fuzzyQueryBook(QueryFavBookReq queryFavBookReq){
        String userId = null;
        String bookName = null;

        if(!ObjectUtils.isEmpty(queryFavBookReq.getUserId())){
            userId = queryFavBookReq.getUserId()
                    .trim();
        }
        if(!ObjectUtils.isEmpty(queryFavBookReq.getBookName())){
            bookName = queryFavBookReq.getBookName()
                    .trim();
        }
        if(ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(bookName)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_4006, "搜索条件不能为空");
        }

        List<BookshelfBInformationRes> list = aBookfavoriteBookMapper.fuzzyquerybookshelefBook(Wrappers.<BookFavorites>query().eq("user_id", queryFavBookReq.getUserId())
                                                                                                                                 .like("book_name", queryFavBookReq.getBookName()));

        return BackResponseEntity.success(ErrCodeEnum.unknown_0, list, "");

    }
}
